﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaiGaoQiaoWeb.Models;
using WaiGaoQiaoWeb.JsonEntities;
using Model.WaiGaoQiao;
using System.Globalization;
using AutoMapper;
using System.Text;

namespace WaiGaoQiaoWeb.Controllers
{
    public class StorageController : Controller
    {
        //
        // GET: /入库/
        protected Work_StorageDetailedInfo storageDetailedInfo = new Work_StorageDetailedInfo(true);
        protected Work_ArticleInfo waInfo = new Work_ArticleInfo();
        private Work_ArticleUnit unit = new Work_ArticleUnit();
        private WorkSupplierInfo supplier = new WorkSupplierInfo(true);
        public ActionResult StorageIndex()
        {
            ViewBag.UnitList = GetUnitList(null);
            ViewBag.ArticleList = GetArticleList();
            return View();
        }
        /// <summary>
        /// 获取供应啥列表
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> GetSupplierList()
        {
            SelectListItem sl = new SelectListItem();
            sl.Selected = true;
            sl.Text = "请选择...";
            sl.Value = "0";
            IList<WorkSupplierInfo> list = supplier.SelSupplierInfo(supplier._Suppliercount, 1, "");
            IList<SelectListItem> selectList =
             list.Select(m => new SelectListItem() { Text = m.Supplier_Name.ToString(), Value = m.ID.ToString() }).ToList();
            selectList.Insert(0, sl);
            return selectList;
        }
        /// <summary>
        ///  获取物品列表
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> GetArticleList()
        {
            SelectListItem sl = new SelectListItem();
            sl.Selected = true;
            sl.Text = "请选择...";
            sl.Value = "0";
            IList<Work_ArticleInfo> list = waInfo.GetAllCon_Article(" AND priorID!=0 union (select ID,ArticleNo,ArticleName,ArticleUnit,PriorID,GetType,Color  from  dbo.Work_Article where priorid=0 and id not in  (select priorid from work_article where priorid!=0))");
            IList<SelectListItem> selectList =
             list.Select(m => new SelectListItem() { Text = m.ArticleName.ToString(), Value = m.ID.ToString() }).ToList();
            selectList.Insert(0, sl);
            return selectList;
        }
        /// <summary>
        /// 获取规格列表
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> GetUnitList(int? id)
        {
            if (!id.HasValue)
            {
                IDictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(0, "请选择...");
                IList<SelectListItem> selectList =
                 dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
                return selectList;
            }
            else
            {
                Work_ArticleInfo idinfo = waInfo.GetCon_ArticleById(Convert.ToInt32(id));
                string[] charUnit = null;
                string[] charUnitId = null;
                if (!string.IsNullOrEmpty(idinfo.ArticleUnit))
                {
                    idinfo.ArticleUnitId = idinfo.ArticleUnit;
                    idinfo.ArticleUnit = RtnStringUnit(idinfo.ArticleUnit);
                    charUnit = idinfo.ArticleUnit.Split(',');
                    charUnitId = idinfo.ArticleUnitId.Split(',');
                }

                IDictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(0, "请选择...");
                if (charUnitId != null && charUnitId.Length > 0)
                {
                    for (int i = 0; i < charUnitId.Length; i++)
                    {
                        dic.Add(Convert.ToInt32(charUnitId[i]), charUnit[i]);
                    }
                }
                IList<SelectListItem> selectList =
                    dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
                return selectList;
            }
        }
        /// <summary>
        /// 根据id获取劳保物资对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult RtnStorageInfo(int? Id)
        {
            if (Id.HasValue)
            {
                Work_ArticleInfo idinfo = waInfo.GetCon_ArticleById(Convert.ToInt32(Id));
                return Json(idinfo);
            }
            else
            {

                return Json(null);
            }
        }
        /// <summary>
        /// 返回物资规格
        /// </summary>
        /// <param name="strUnit"></param>
        /// <returns></returns>
        public string RtnStringUnit(string strUnit)
        {
            StringBuilder rtnString = new StringBuilder();
            if (!string.IsNullOrEmpty(strUnit))
            {
                if (strUnit.IndexOf(',') > 0)
                {
                    string[] charUnit = strUnit.Split(',');
                    for (int i = 0; i < charUnit.Length; i++)
                    {
                        rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(charUnit[i])).Unit + ",");

                    }
                }
                else
                {
                    rtnString.Append(unit.GetCon_ArticleUnitById(Convert.ToInt32(strUnit)).Unit);
                }
            }
            return rtnString.ToString();
        }
        /// <summary>
        /// 根据id获取劳保物资对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult RtnStorageInfoForUnit(int? Id)
        {
            if (Id.HasValue)
            {
                Work_ArticleInfo idinfo = waInfo.GetCon_ArticleById(Convert.ToInt32(Id));
                if (!string.IsNullOrEmpty(idinfo.ArticleUnit))
                {
                    idinfo.ArticleUnitId = idinfo.ArticleUnit;
                    idinfo.ArticleUnit = RtnStringUnit(idinfo.ArticleUnit);
                }
                return Json(idinfo);
            }
            else
            {

                return Json(null);
            }
        }

        /// <summary>
        /// 转到添加或修改界面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddStorage(int? id)
        {

            StockVM idvm = new StockVM();
            ViewBag.ArticleList = GetArticleList();
            ViewBag.SupplierList = GetSupplierList();
            if (!id.HasValue)
            {
                ViewBag.UnitList = GetUnitList(null);
                idvm.ID = 0;
                idvm.Count = 0;
                idvm.RecordDateTime = DateTime.Now;
                idvm.OperatorID = ((LogOnModel)System.Web.HttpContext.Current.Session["user"]).LogName;
                idvm.OrderNo = storageDetailedInfo.BuliderOrderNo();
                idvm.StorageDt1 = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {

                Work_StorageDetailedInfo idinfo = storageDetailedInfo.GetAllStorageDetailed(Convert.ToInt32(id));
                ViewBag.UnitList = GetUnitList(idinfo.Article_ID);
                Mapper.DynamicMap(idinfo, idvm);
                idvm.StorageDt1 = idinfo.StorageDt.ToString("yyyy-MM-dd");

            }
            return View(idvm);
        }

        /// <summary>
        /// 获得劳保入库数据
        /// </summary>
        /// <param name="pvm"></param>
        /// <returns></returns>
        public JsonResult GetStorageDetailList(PageVM pvm)
        {
            if (string.IsNullOrEmpty(pvm.query))
            {
                pvm.query = "and OrderNo = ''";
            }
            string condition = pvm.query;
            JsonFlexiGridData jsonFlexiGridData = new JsonFlexiGridData();
            jsonFlexiGridData.page = pvm.page;
            jsonFlexiGridData.total = storageDetailedInfo.GetStorageDetailedCount(condition);
            IList<Work_StorageDetailedInfo> list = storageDetailedInfo.GetAllStorageDetailed(condition, pvm.rp, pvm.page);
            List<string> v;
            foreach (Work_StorageDetailedInfo ida in list)
            {
                #region
                v = new List<string>();
                v.Add(ida.ID.ToString());
                v.Add(ida.StorageDt.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo));
                v.Add(waInfo.GetCon_ArticleById(ida.Article_ID).ArticleName);
                v.Add(ida.Article_Color);
                v.Add(!string.IsNullOrEmpty(ida.Article_Unit) ? unit.GetCon_ArticleUnitById(Convert.ToInt32(ida.Article_Unit)).Unit : "");
                v.Add(ida.Count.ToString());
                v.Add(supplier.GetSupplierInfoOne(ida.Supplier).Supplier_Name);
                v.Add(ida.Remark);
                v.Add(ida.RecordDateTime.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo));
                v.Add(ida.OperatorID);
                #endregion
                FlexiGridRow fgr = new FlexiGridRow()
                {
                    id = ida.ID.ToString(),
                    cell = v
                };
                jsonFlexiGridData.rows.Add(fgr);
            }
            return Json(jsonFlexiGridData);
        }
        /// <summary>
        /// 根据订单编号查询新添加的数据
        /// </summary>
        /// <param name="pvm"></param>
        /// <returns></returns>
        public JsonResult GetStorageDetailListByOrderNo(PageVM pvm)
        {
            string condition = "and OrderNo = '" + pvm.query + "'";
            JsonFlexiGridData jsonFlexiGridData = new JsonFlexiGridData();
            jsonFlexiGridData.page = pvm.page;
            jsonFlexiGridData.total = storageDetailedInfo.GetStorageDetailedCount(condition);
            IList<Work_StorageDetailedInfo> list = storageDetailedInfo.GetAllStorageDetailed(condition, pvm.rp, pvm.page);
            List<string> v;
            foreach (Work_StorageDetailedInfo ida in list)
            {
                #region
                v = new List<string>();
                v.Add(ida.ID.ToString());
                v.Add(ida.StorageDt.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo));
                v.Add(waInfo.GetCon_ArticleById(ida.Article_ID).ArticleName);
                v.Add(ida.Article_Color);
                v.Add(!string.IsNullOrEmpty(ida.Article_Unit) ? unit.GetCon_ArticleUnitById(Convert.ToInt32(ida.Article_Unit)).Unit : "");
                v.Add(ida.Count.ToString());
                v.Add(supplier.GetSupplierInfoOne(ida.Supplier).Supplier_Name);
                v.Add(ida.Remark);
                v.Add(ida.RecordDateTime.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo));
                v.Add(ida.OperatorID);
                #endregion
                FlexiGridRow fgr = new FlexiGridRow()
                {
                    id = ida.ID.ToString(),
                    cell = v
                };
                jsonFlexiGridData.rows.Add(fgr);
            }
            return Json(jsonFlexiGridData);
        }

        /// <summary>
        /// 删除劳保物资
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(int id)
        {
            int rowcount = storageDetailedInfo.DeleteStorageDetailed(id);
            return Json(rowcount);

        }
        /// <summary>
        /// 保存劳保数据
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveStoryDetail(StockVM vm)
        {
            if (ModelState.IsValid)
            {
                Work_StorageDetailedInfo info = new Work_StorageDetailedInfo();
                Mapper.DynamicMap(vm, info);
                info.StorageDt = Convert.ToDateTime(vm.StorageDt1);
                storageDetailedInfo.SaveStorageDetailed(info);
                return Json(true);
            }
            else
            {
                return Json(false);
            }


        }

    }
}
